package phase01.module4.code.question3;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CopyFolderRunnable implements Runnable {
    private final Path src;
    private final Path dest;

    public CopyFolderRunnable(Path target, Path dest) {
        this.src = target;
        this.dest = dest;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getId() + ": " + src + " -> " + dest);
        if (!Files.isDirectory(src)) {
            System.out.println(src + "不是一个文件夹!");
        }
        if (!Files.isDirectory(dest)) {
            System.out.println(dest + "不是一个文件夹!");
        }
        if (!Files.isReadable(src)) {
            System.out.println("没有权限读取文件夹：" + src);
        }
        if (!Files.isWritable(dest)) {
            System.out.println("没有权限写入文件夹：" + dest);
        }
        try {
            Files.list(src).filter(Files::isRegularFile).forEach(file -> {
                Path destFilePath = dest.resolve(src.relativize(file));
                if (!Files.exists(destFilePath)) {
                    try {
                        Files.copy(file, destFilePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
